package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.model.TbSpecificationOption;
import com.dongdongshop.page.PageParms;
import com.dongdongshop.page.PageResult;
import com.dongdongshop.service.SpecificationService;
import com.dongdongshop.vo.SpecificationOptionVO;
import com.dongdongshop.vo.SpecificationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spec")
@RefreshScope
public class SpecificationController {

    @Autowired
    private SpecificationService ss;

    @PostMapping("selectAll")
    public Result selectAll(@RequestBody PageParms<SpecificationVO> parms) {
        try {
            PageResult<SpecificationVO> pageResult = ss.selectAll(parms);
            return Result.OK().setData(pageResult);
        } catch (Exception e) {
            return Result.FALL();
        }
    }

    @PostMapping("addSpec")
    public Result addSpec(SpecificationVO specVo, String optionListJson) {
        try {
            List<SpecificationOptionVO> specOptionList = JSONObject.parseArray(optionListJson, SpecificationOptionVO.class);
            ss.addSpec(specVo, specOptionList);
            return Result.OK();
        } catch (Exception e) {
            return Result.FALL();
        }

    }

    @PostMapping("selectById")
    public Result selectById(@RequestParam Long id) {
        try {
            SpecificationVO specVO = ss.selectById(id);
            return Result.OK().setData(specVO);
        } catch (Exception e) {
            return Result.FALL();
        }

    }

    @PostMapping("updateSpec")
    public Result updateSpec(String tbSpecification) {
        try {
            SpecificationVO specOptionList = JSONObject.parseObject(tbSpecification, SpecificationVO.class);
            ss.updateSpec(specOptionList);
            return Result.OK();
        } catch (Exception e) {
            return Result.FALL();
        }

    }

    @PostMapping("delete")
    public Result delete(Long[] ids) {
        try {
            ss.delete(ids);
            return Result.OK();
        } catch (Exception e) {
            return Result.FALL();
        }

    }

    @PostMapping("delThis")
    public Result delThis(Long specId) {
        try {
            ss.delThis(specId);
            return Result.OK();
        } catch (Exception e) {
            return Result.FALL();
        }
    }

    @PostMapping("specList")
    public Result specList() {
        List<SpecificationVO> pageResult = ss.specList();
        return Result.OK().setData(pageResult);
    }


}
